Originally Posted by
jimblumberg
C++ passes everything into functions by value. This means that the compiler copies the variable when passing to a function. Copying a vector or any other non-trivially constructed class (like a std::string) can be expensive to copy therefore you want to try to eliminate any unnecessary copying.
In C++ this can be done two ways, passing by reference, or passing by pointer reference.
For more information I suggest you use your favourite search engine and look up some documentation on "C++ pass by reference".
Like so?:
Code:
int gcd(const int& a, const int& b) {
return a == 0 ? b : gcd(b % a, a);
}
unsigned int find_gcd(const vector <int>& arr) {
unsigned int result = arr[0];
for (unsigned int i = 1; i < arr.size(); i++)
result = gcd(arr[i], result);
return result;
}
I'm still a still confused about when pointer is used over reference and why "const" is used though.
Thanks for the tip jim. I would have never known about this.